<template>
  <div class="app-container">
    <el-card shadow="never">
      <template #header>
        <div class="card-header">
          <h3>{{ isEdit ? '编辑科室' : '新增科室' }}</h3>
        </div>
      </template>
      
      <el-form 
        ref="formRef" 
        :model="form" 
        :rules="rules" 
        label-width="120px"
        label-position="right"
        status-icon
        v-loading="loading"
      >
        <el-divider content-position="left">基本信息</el-divider>
        
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="科室编码" prop="code">
              <el-input 
                v-model="form.code" 
                placeholder="请输入科室编码，如NKXS" 
                :disabled="isEdit"
              />
            </el-form-item>
          </el-col>
          
          <el-col :span="8">
            <el-form-item label="科室名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入科室名称，如内科学系" />
            </el-form-item>
          </el-col>
          
          <el-col :span="8">
            <el-form-item label="科室类型" prop="category">
              <el-select v-model="form.category" placeholder="请选择科室类型" style="width: 100%">
                <el-option label="临床" value="临床" />
                <el-option label="医技" value="医技" />
                <el-option label="行政" value="行政" />
                <el-option label="其他" value="其他" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="联系电话" prop="telephone">
              <el-input v-model="form.telephone" placeholder="请输入联系电话" />
            </el-form-item>
          </el-col>
          
          <el-col :span="8">
            <el-form-item label="楼层" prop="floor">
              <el-input v-model="form.floor" placeholder="请输入楼层，如1楼" />
            </el-form-item>
          </el-col>
          
          <el-col :span="8">
            <el-form-item label="状态" prop="status">
              <el-select v-model="form.status" placeholder="请选择状态" style="width: 100%">
                <el-option label="启用" value="启用" />
                <el-option label="禁用" value="禁用" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="科室主任" prop="headDoctor">
              <div class="head-doctor-container">
                <el-select 
                  v-model="form.headDoctor" 
                  placeholder="请选择科室主任" 
                  clearable
                  filterable
                  :loading="loading"
                  class="head-doctor-select"
                >
                  <el-option 
                    v-for="item in doctorOptions" 
                    :key="item.id" 
                    :label="item.name" 
                    :value="item.id" 
                  />
                </el-select>
                <el-button 
                  v-if="form.headDoctor && isEdit" 
                  type="primary" 
                  link
                  @click="showHeadDoctorInfo"
                >
                  查看详情
                </el-button>
              </div>
            </el-form-item>
          </el-col>
          
          <el-col :span="8">
            <el-form-item label="位置" prop="location">
              <el-input v-model="form.location" placeholder="请输入科室位置" />
            </el-form-item>
          </el-col>
          
          <el-col :span="8">
            <el-form-item label="排序" prop="order">
              <el-input-number v-model="form.order" :min="1" :max="1000" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row>
          <el-col :span="24">
            <el-form-item label="描述" prop="description">
              <el-input 
                v-model="form.description" 
                type="textarea" 
                placeholder="请输入科室描述" 
                :rows="3"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <div class="form-actions">
          <el-button @click="goBack">取消</el-button>
          <el-button type="primary" @click="submitForm" :loading="submitting">提交</el-button>
        </div>
      </el-form>
      
      <!-- 科室医生列表展示，仅在编辑模式显示 -->
      <div v-if="isEdit && !loading" class="doctors-section">
        <el-divider content-position="left">科室医生</el-divider>
        
        <el-alert
          title="此处仅供查看科室关联的医生信息，如需编辑医生信息请前往医生管理页面"
          type="info"
          :closable="false"
          show-icon
          style="margin-bottom: 15px;"
        />
        
        <el-table
          v-if="departmentDoctors.length > 0"
          :data="departmentDoctors"
          style="width: 100%"
          border
          stripe
        >
          <el-table-column prop="staffId" label="工号" width="120" />
          <el-table-column prop="name" label="姓名" width="120" />
          <el-table-column prop="title" label="职称" width="150" />
          <el-table-column label="专长">
            <template #default="scope">
              <el-tag 
                v-for="(specialty, index) in scope.row.specialties" 
                :key="index"
                size="small"
                class="specialty-tag"
              >
                {{ specialty }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table>
        
        <el-empty 
          v-else 
          description="暂无医生数据" 
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { departmentAPI, doctorAPI } from '@/utils/api'

const router = useRouter()
const route = useRoute()
const departmentId = ref(route.params.id)
const isEdit = computed(() => !!departmentId.value)

// 表单数据
const formRef = ref(null)
const loading = ref(false)
const submitting = ref(false)

// 下拉选项
const departmentOptions = ref([])
const doctorOptions = ref([])

// 表单数据
const form = reactive({
  code: '',
  name: '',
  category: '临床',
  description: '',
  location: '',
  floor: '',
  telephone: '',
  headDoctor: '',
  order: 100,
  status: '启用'
})

// 科室关联的医生列表
const departmentDoctors = ref([])
// 科室主任信息
const headDoctorInfo = ref(null)

// 表单验证规则
const rules = {
  code: [
    { required: true, message: '请输入科室编码', trigger: 'blur' },
    { pattern: /^[A-Z0-9]{2,10}$/, message: '科室编码只能包含大写字母和数字，长度为2-10个字符', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入科室名称', trigger: 'blur' }
  ],
  category: [
    { required: true, message: '请选择科室类型', trigger: 'change' }
  ],
  telephone: [
    { pattern: /^(\d{3,4}-\d{7,8}|\d{11})$/, message: '请输入正确的电话号码格式', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ],
  order: [
    { type: 'number', message: '排序必须为数字', trigger: 'blur' }
  ]
}

// 获取科室列表
const fetchDepartments = async () => {
  try {
    console.log('开始获取科室列表...')
    const res = await departmentAPI.getDepartments()
    console.log('科室列表API响应:', res)
    
    // 处理不同的响应格式
    let departments = []
    
    if (res.success && res.data && res.data.departments) {
      departments = res.data.departments
      console.log('直接从res.data.departments获取科室数据:', departments)
    } else if (res.data && res.data.success && res.data.data && res.data.data.departments) {
      departments = res.data.data.departments
      console.log('从res.data.data.departments获取科室数据:', departments)
    } else if (Array.isArray(res)) {
      departments = res
      console.log('直接从响应数组获取科室数据:', departments)
    } else if (res.data && Array.isArray(res.data)) {
      departments = res.data
      console.log('从res.data数组获取科室数据:', departments)
    } else {
      console.error('获取科室列表失败：响应格式不符合预期', res)
      ElMessage.warning('科室数据格式异常，请联系管理员')
      return
    }
    
    // 确保每个科室对象具有id和name属性
    departmentOptions.value = departments
      .filter(dept => dept && (dept.id || dept._id) && dept.id !== departmentId.value) // 过滤掉当前编辑的科室
      .map(dept => {
        // 标准化科室对象
        return {
          id: dept.id || dept._id || '',
          name: dept.name || '未命名科室',
          code: dept.code || '',
          category: dept.category || ''
        }
      })
    
    console.log('处理后的科室选项:', departmentOptions.value)
  } catch (error) {
    console.error('获取科室列表失败', error)
    ElMessage.error('获取科室列表失败，请刷新页面重试')
  }
}

// 获取科室详情
const fetchDepartmentDetail = async () => {
  if (!departmentId.value) return
  
  loading.value = true
  try {
    console.log('获取科室详情, ID:', departmentId.value)
    const res = await departmentAPI.getDepartment(departmentId.value)
    console.log('科室详情API响应:', res)
    
    // 处理不同的响应格式
    let departmentData = null
    
    if (res.success && res.data) {
      // 直接使用data字段作为科室数据
      departmentData = res.data
      console.log('从res.data获取科室数据:', departmentData)
    } else if (res.id || res._id) {
      // 响应本身是科室对象
      departmentData = res
      console.log('响应本身是科室对象:', departmentData)
    } else {
      console.error('获取科室详情失败：响应格式不符合预期', res)
      ElMessage.error('科室数据格式异常，请联系管理员')
      loading.value = false
      return
    }
    
    if (departmentData) {
      // 填充表单数据
      Object.keys(form).forEach(key => {
        if (departmentData[key] !== undefined) {
          form[key] = departmentData[key]
        }
      })
      
      // 处理特殊字段
      // 如果后端返回的是category字段，而前端使用的是type字段
      if (departmentData.category && !form.category) {
        form.category = departmentData.category
      }
      
      // 确保parentId是字符串类型
      if (form.parentId) {
        form.parentId = String(form.parentId)
      }
      
      // 保存科室关联的医生数据
      if (departmentData.doctors && Array.isArray(departmentData.doctors)) {
        departmentDoctors.value = departmentData.doctors
        console.log('科室关联的医生数据:', departmentDoctors.value)
      }
      
      // 保存科室主任信息
      if (departmentData.headDoctorInfo) {
        headDoctorInfo.value = departmentData.headDoctorInfo
        console.log('科室主任信息:', headDoctorInfo.value)
      }
      
      console.log('表单数据设置完成:', form)
    } else {
      ElMessage.error('获取科室详情失败：科室数据为空')
    }
  } catch (error) {
    console.error('获取科室详情失败', error)
    ElMessage.error('获取科室详情失败')
  } finally {
    loading.value = false
  }
}

// 获取医生列表
const fetchDoctors = async () => {
  try {
    console.log('开始获取医生列表...')
    const res = await doctorAPI.getDoctors({ limit: 100 })
    console.log('医生列表API响应:', res)
    
    // 处理不同的响应格式
    let doctors = []
    
    if (res.success && res.data && res.data.doctors) {
      doctors = res.data.doctors
      console.log('直接从res.data.doctors获取医生数据:', doctors)
    } else if (res.data && res.data.success && res.data.data && res.data.data.doctors) {
      doctors = res.data.data.doctors
      console.log('从res.data.data.doctors获取医生数据:', doctors)
    } else if (Array.isArray(res)) {
      doctors = res
      console.log('直接从响应数组获取医生数据:', doctors)
    } else if (res.data && Array.isArray(res.data)) {
      doctors = res.data
      console.log('从res.data数组获取医生数据:', doctors)
    } else {
      console.error('获取医生列表失败：响应格式不符合预期', res)
      ElMessage.warning('医生数据格式异常，请联系管理员')
      return
    }
    
    // 确保每个医生对象具有id和name属性
    doctorOptions.value = doctors
      .filter(doc => doc && (doc.id || doc._id))
      .map(doc => {
        // 标准化医生对象
        return {
          id: doc.id || doc._id || '',
          name: doc.name || '未命名医生',
          title: doc.title || ''
        }
      })
    
    console.log('处理后的医生选项:', doctorOptions.value)
  } catch (error) {
    console.error('获取医生列表失败', error)
    ElMessage.error('获取医生列表失败，请刷新页面重试')
  }
}

// 提交表单
const submitForm = async () => {
  await formRef.value.validate(async (valid) => {
    if (!valid) return
    
    submitting.value = true
    try {
      // 准备提交的数据
      const departmentData = { ...form }
      
      // 确保parentId是有效值或null
      if (!departmentData.parentId || departmentData.parentId === '') {
        delete departmentData.parentId
      } else {
        // 确保parentId是字符串类型
        departmentData.parentId = String(departmentData.parentId)
      }
      
      // 确保order是数字类型
      if (departmentData.order !== undefined) {
        departmentData.order = Number(departmentData.order)
      }
      
      // 移除不需要的字段
      delete departmentData.type
      
      // 如果是编辑模式，删除code字段，避免"Unknown field"验证错误
      if (isEdit.value) {
        delete departmentData.code
      }
      
      console.log('提交的科室数据:', departmentData)
      
      let res
      if (isEdit.value) {
        res = await departmentAPI.updateDepartment(departmentId.value, departmentData)
      } else {
        res = await departmentAPI.createDepartment(departmentData)
      }
      
      console.log(isEdit.value ? '更新科室响应:' : '创建科室响应:', res)
      
      // 处理不同的响应格式
      let success = false
      let message = ''
      
      if (res.success) {
        success = true
      } else if (res.data && res.data.success) {
        success = true
      } else if (res.data && res.data.message) {
        message = res.data.message
      } else if (res.message) {
        message = res.message
      }
      
      if (success) {
        ElMessage.success(isEdit.value ? '科室更新成功' : '科室创建成功')
        goBack()
      } else {
        ElMessage.error(message || (isEdit.value ? '科室更新失败' : '科室创建失败'))
      }
    } catch (error) {
      console.error(isEdit.value ? '科室更新失败' : '科室创建失败', error)
      if (error.response && error.response.data) {
        console.error('错误详情:', error.response.data)
        if (error.response.data.errors) {
          const errorMessages = Object.entries(error.response.data.errors)
            .map(([field, msgs]) => `${field}: ${msgs.join(', ')}`)
            .join('; ')
          ElMessage.error(`验证失败: ${errorMessages}`)
        } else {
          ElMessage.error(error.response.data.message || (isEdit.value ? '科室更新失败' : '科室创建失败'))
        }
      } else {
        ElMessage.error(isEdit.value ? '科室更新失败' : '科室创建失败')
      }
    } finally {
      submitting.value = false
    }
  })
}

// 返回上一页
const goBack = () => {
  router.back()
}

// 显示科室主任详情
const showHeadDoctorInfo = () => {
  if (!headDoctorInfo.value) {
    ElMessage.warning('未找到科室主任详细信息')
    return
  }
  
  const specialties = headDoctorInfo.value.specialties 
    ? headDoctorInfo.value.specialties.join('、') 
    : '暂无专长信息'
  
  ElMessageBox.alert(
    `<div>
      <p><strong>工号：</strong>${headDoctorInfo.value.staffId || '未设置'}</p>
      <p><strong>姓名：</strong>${headDoctorInfo.value.name}</p>
      <p><strong>职称：</strong>${headDoctorInfo.value.title || '未设置'}</p>
      <p><strong>专长：</strong>${specialties}</p>
    </div>`,
    '科室主任信息',
    {
      dangerouslyUseHTMLString: true,
      confirmButtonText: '关闭'
    }
  )
}

// 生命周期钩子
onMounted(() => {
  fetchDepartments()
  fetchDoctors()
  
  if (isEdit.value) {
    fetchDepartmentDetail()
  }
})
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.form-actions {
  display: flex;
  justify-content: center;
  margin-top: 30px;
  gap: 20px;
}
.doctors-section {
  margin-top: 30px;
}
.specialty-tag {
  margin-right: 5px;
  margin-bottom: 5px;
}
.head-doctor-container {
  display: flex;
  align-items: center;
}
.head-doctor-select {
  flex: 1;
}
</style> 